package com.tzkyzj.tiremanagersystem.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.tzkyzj.tiremanagersystem.R;
import com.tzkyzj.tiremanagersystem.api.AuthApiService;
import com.tzkyzj.tiremanagersystem.api.TireApiService;
import com.tzkyzj.tiremanagersystem.eneities.Tire;
import com.tzkyzj.tiremanagersystem.network.ApiClient;
import com.tzkyzj.tiremanagersystem.viewmodel.TireListAdapter;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.util.*;

import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.text.TextWatcher;
import java.util.Timer;
import java.util.TimerTask;

public class TireListActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private TireListAdapter adapter;
    private List<Tire> tireList = new ArrayList<>();
    private ProgressBar progressBar;
    private LinearLayout statsLayout;
    private TextView tvTotalTires, tvActiveTires, tvScrappedTires, tvRepairedTires;
    private Spinner spinnerCompany, spinnerStatus;
    private TireApiService apiService;

    // 存储动态获取的数据
    private List<String> transportCompanies = new ArrayList<>();
    private List<String> statusOptions = new ArrayList<>();

    private AutoCompleteTextView etSearchTireNumber, etSearchPlateNumber;
    private ArrayAdapter<String> tireNumberAdapter, plateNumberAdapter;

    // 在 TireListActivity 类顶部添加
    private static final int REQUEST_CODE_BATCH_ADD = 1001;
    private static final int REQUEST_CODE_SINGLE_ADD = 1002;
    private static final int REQUEST_CODE_EDIT_TIRE = 1003; // 新增：编辑轮胎请求码
    private FloatingActionButton fabAddBatch;

    private SharedPreferences sharedPreferences;
    private String userRole;
    private String userCompany; // 当前用户所属公司
    private String userPlateNumber; // 当前用户车牌号（司机角色）
    private MenuItem menuUserManagement;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 先检查登录状态，再设置布局
        checkLoginStatus();

        // 如果已经跳转到登录页面，就不需要执行后面的代码
        if (isFinishing()) {
            return;
        }

        setContentView(R.layout.activity_tire_list);

        // 初始化其他组件...
        initViews();
        setupRecyclerView();
        setupRetrofit();
        setupSearch();
        setupAutoComplete();
        loadDropdownData();
        initBatchAddButton();
        initAddTireButton();

        // 新增：初始化用户信息显示（必须在setContentView之后）
        initUserInfo();

        // 获取完整的用户信息
        fetchCompleteUserInfo();
    }

    /**
     * 初始化用户信息显示
     */
    private void initUserInfo() {
        sharedPreferences = getSharedPreferences("user_prefs", MODE_PRIVATE);
        String username = sharedPreferences.getString("username", null);
        userRole = sharedPreferences.getString("role", "DRIVER");
        userCompany = sharedPreferences.getString("company", null); // 获取用户所属公司
        userPlateNumber = sharedPreferences.getString("plateNumber", null); // 获取用户车牌号

        // 记录用户信息用于调试
        Log.d("TireListActivity", "用户信息 - 用户名: " + username +
                ", 角色: " + userRole +
                ", 公司: " + userCompany +
                ", 车牌: " + userPlateNumber);

        if (username != null) {
            updateUserInfoDisplay(username, userRole);
        }
    }
    private void checkLoginStatus() {
        sharedPreferences = getSharedPreferences("user_prefs", MODE_PRIVATE);
        String username = sharedPreferences.getString("username", null);
        userRole = sharedPreferences.getString("role", "DRIVER");
        userCompany = sharedPreferences.getString("company", null);
        userPlateNumber = sharedPreferences.getString("plateNumber", null);

        Log.d("TireListActivity", "登录检查 - 用户名: " + username);

        // 关键修改：不仅要检查用户名，还要验证服务器 Session
        if (username == null || username.isEmpty()) {
            // 未登录，跳转到登录页面
            Log.d("TireListActivity", "未登录，跳转到登录页");
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            finish();
            return;
        } else {
            Log.d("TireListActivity", "本地用户信息存在，验证服务器 Session");
            // 用户信息存在，但需要验证服务器 Session 是否有效
            verifyServerSession();
        }
    }

    /**
     * 验证服务器 Session 是否有效
     */
    private void verifyServerSession() {
        Retrofit retrofit = ApiClient.getClient();
        if (retrofit == null) {
            Log.e("TireListActivity", "ApiClient 不可用");
            handleSessionInvalid();
            return;
        }

        AuthApiService authApiService = retrofit.create(AuthApiService.class);
        Call<Map<String, Object>> call = authApiService.getUserInfo();
        call.enqueue(new Callback<Map<String, Object>>() {
            @Override
            public void onResponse(Call<Map<String, Object>> call, Response<Map<String, Object>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    Map<String, Object> data = response.body();
                    Boolean authenticated = (Boolean) data.get("authenticated");

                    if (authenticated != null && authenticated) {
                        // Session 有效，继续加载页面
                        Log.d("TireListActivity", "服务器 Session 验证成功");
                        loadPageData();
                    } else {
                        // Session 无效
                        Log.e("TireListActivity", "服务器 Session 无效");
                        handleSessionInvalid();
                    }
                } else {
                    // 请求失败，Session 可能无效
                    Log.e("TireListActivity", "Session 验证请求失败: " + response.code());
                    if (response.code() == 401) {
                        handleSessionInvalid();
                    } else {
                        // 网络问题，尝试继续加载
                        loadPageData();
                    }
                }
            }

            @Override
            public void onFailure(Call<Map<String, Object>> call, Throwable t) {
                Log.e("TireListActivity", "Session 验证网络错误: " + t.getMessage());
                // 网络问题，尝试继续加载
                loadPageData();
            }
        });
    }

    /**
     * Session 无效的处理
     */
    private void handleSessionInvalid() {
        runOnUiThread(() -> {
            Log.e("TireListActivity", "Session 无效，需要重新登录");
            Toast.makeText(TireListActivity.this, "登录已过期，请重新登录", Toast.LENGTH_LONG).show();

            // 清除本地用户数据
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.clear();
            editor.apply();

            // 清除 Cookie
            ApiClient.clearClient();

            // 跳转到登录页面
            Intent intent = new Intent(TireListActivity.this, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        });
    }

    /**
     * 加载页面数据（Session 验证通过后调用）
     */
    private void loadPageData() {
        runOnUiThread(() -> {
            // 执行原来的 onCreate 剩余代码
            setContentView(R.layout.activity_tire_list);
            initViews();
            setupRecyclerView();
            setupRetrofit();
            setupSearch();
            setupAutoComplete();
            loadDropdownData();
            initBatchAddButton();
            initAddTireButton();
            initUserInfo();
            fetchCompleteUserInfo();
        });
    }

    private void updateUserInfoDisplay(String username, String role) {
        TextView tvUserInfo = findViewById(R.id.tv_user_info);
        if (tvUserInfo != null) {
            String roleText = "";
            switch (role) {
                case "ADMIN":
                    roleText = "管理员";
                    break;
                case "COMPANY":
                    roleText = "运输公司";
                    break;
                case "DRIVER":
                    roleText = "司机";
                    break;
                default:
                    roleText = "用户";
            }
            tvUserInfo.setText(username + " (" + roleText + ")");
        }

        // 初始化登出按钮
        ImageButton btnLogout = findViewById(R.id.btn_logout);
        if (btnLogout != null) {
            btnLogout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showLogoutConfirmation();
                }
            });
        }
    }

    // 在 initViews() 方法中添加用户管理按钮
    private void initViews() {
        recyclerView = findViewById(R.id.recyclerView);
        progressBar = findViewById(R.id.progressBar);
        statsLayout = findViewById(R.id.statsLayout);

        // 统计视图
        tvTotalTires = findViewById(R.id.tv_total_tires);
        tvActiveTires = findViewById(R.id.tv_active_tires);
        tvScrappedTires = findViewById(R.id.tv_scrapped_tires);
        tvRepairedTires = findViewById(R.id.tv_repaired_tires);

        // 搜索视图
        etSearchTireNumber = findViewById(R.id.et_search_tire_number);
        etSearchPlateNumber = findViewById(R.id.et_search_plate_number);
        spinnerCompany = findViewById(R.id.spinner_company);
        spinnerStatus = findViewById(R.id.spinner_status);

        // 根据用户角色设置运输公司和车牌号的可用性
        setupRoleBasedFilters();

        // 新增：用户管理按钮（仅管理员可见）
        ImageButton btnUserManagement = findViewById(R.id.btn_user_management);
        if (btnUserManagement != null) {
            btnUserManagement.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
                    String role = prefs.getString("role", "");

                    if ("ADMIN".equals(role)) {
                        // 使用WebView打开用户管理页面
                        Intent intent = new Intent(TireListActivity.this, UserManagementWebActivity.class);
                        startActivity(intent);
                    } else {
                        Toast.makeText(TireListActivity.this,
                                "权限不足，只有管理员可以访问用户管理", Toast.LENGTH_SHORT).show();
                    }
                }
            });

            // 根据用户角色显示/隐藏用户管理按钮
            btnUserManagement.setVisibility("ADMIN".equals(userRole) ? View.VISIBLE : View.GONE);
        }

        // 先设置空的适配器，等数据加载后再更新
        setupEmptySpinners();
    }

    /**
     * 根据用户角色设置筛选条件的可用性
     */
    /**
     * 根据用户角色设置筛选条件的可用性
     */
    private void setupRoleBasedFilters() {
        switch (userRole) {
            case "ADMIN":
                // 管理员：可以查看所有运输公司和所有车牌号
                spinnerCompany.setEnabled(true);
                etSearchPlateNumber.setEnabled(true);
                etSearchPlateNumber.setHint("输入车牌号搜索");
                break;

            case "COMPANY":
                // 运输公司：固定为当前公司，可以查看所有车牌号
                spinnerCompany.setEnabled(false);
                etSearchPlateNumber.setEnabled(true);
                etSearchPlateNumber.setHint("输入车牌号搜索");
                break;

            case "DRIVER":
                // 司机：固定为当前公司和当前车牌号
                spinnerCompany.setEnabled(false);
                etSearchPlateNumber.setEnabled(false);
                if (userPlateNumber != null && !userPlateNumber.isEmpty()) {
                    etSearchPlateNumber.setText(userPlateNumber);
                }
                etSearchPlateNumber.setHint("固定车牌号");
                break;

            default:
                // 默认情况：启用所有筛选
                spinnerCompany.setEnabled(true);
                etSearchPlateNumber.setEnabled(true);
                etSearchPlateNumber.setHint("输入车牌号搜索");
                break;
        }

        Log.d("TireListActivity", "设置角色筛选 - 角色: " + userRole +
                ", 公司: " + userCompany + ", 车牌: " + userPlateNumber);
    }

    private void loadDropdownData() {
        showLoading(true);

        // 根据用户角色加载运输公司数据
        loadTransportCompaniesByRole();

        // 加载状态选项（所有角色都一样）
        loadStatusOptions();

        // 更新车牌号字段显示
        updatePlateNumberField();
    }

    // 添加菜单创建方法
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        menuUserManagement = menu.findItem(R.id.menu_user_management);

        // 根据用户角色显示/隐藏用户管理菜单
        if (menuUserManagement != null) {
            menuUserManagement.setVisible("ADMIN".equals(userRole));
        }

        return true;
    }

    // 添加菜单项点击处理
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.menu_user_management) {
            // 跳转到用户管理页面
            Intent intent = new Intent(this, UserManagementActivity.class);
            startActivity(intent);
            return true;
        } else if (id == R.id.menu_logout) {
            showLogoutConfirmation();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * 显示登出确认对话框
     */
    private void showLogoutConfirmation() {
        new AlertDialog.Builder(this)
                .setTitle("确认退出登录")
                .setMessage("确定要退出当前账号吗？")
                .setPositiveButton("退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        clearLoginStatus();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void clearLoginStatus() {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear(); // 清除所有数据
        editor.apply();

        // 清除 Cookie
        ApiClient.clearClient();

        // 跳转到登录页面，并清除所有之前的 Activity
        Intent intent = new Intent(TireListActivity.this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }

    /**
     * 初始化批量添加轮胎按钮
     */
    // 在 TireListActivity 中的 initBatchAddButton 方法
    private void initBatchAddButton() {
        fabAddBatch = findViewById(R.id.fab_add_batch);

        if (fabAddBatch != null) {
            fabAddBatch.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 直接启动 BatchAddTireActivity，不需要传递参数
                    Intent intent = new Intent(TireListActivity.this, BatchAddTireActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_BATCH_ADD);
                    animateButtonClick(v);
                }
            });

            fabAddBatch.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    Toast.makeText(TireListActivity.this, "批量添加轮胎", Toast.LENGTH_SHORT).show();
                    return true;
                }
            });
        } else {
            Log.w("TireListActivity", "批量添加按钮未找到，请检查布局文件");
        }
    }

    /**
     * 初始化普通添加轮胎按钮
     */
    private void initAddTireButton() {
        // 查找普通添加按钮
        Button btnAddTire = findViewById(R.id.btn_add_tire);

        if (btnAddTire != null) {
            btnAddTire.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 跳转到批量添加页面（或者可以跳转到单个添加页面）
                    Intent intent = new Intent(TireListActivity.this, BatchAddTireActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_BATCH_ADD);

                    // 添加点击动画效果
                    animateButtonClick(v);
                }
            });
            Log.d("TireListActivity", "普通添加轮胎按钮初始化成功");
        } else {
            Log.w("TireListActivity", "普通添加轮胎按钮未找到，ID: btn_add_tire");
        }
    }

    /**
     * 按钮点击动画效果
     */
    private void animateButtonClick(View view) {
        // 缩放动画
        view.animate()
                .scaleX(0.9f)
                .scaleY(0.9f)
                .setDuration(100)
                .withEndAction(new Runnable() {
                    @Override
                    public void run() {
                        view.animate()
                                .scaleX(1f)
                                .scaleY(1f)
                                .setDuration(100)
                                .start();
                    }
                })
                .start();
    }

    /**
     * 处理从其他Activity返回的结果
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 检查是否是从批量添加页面返回
        if (requestCode == REQUEST_CODE_BATCH_ADD || requestCode == REQUEST_CODE_SINGLE_ADD) {
            // 检查操作是否成功
            if (resultCode == RESULT_OK) {
                // 添加成功，刷新轮胎列表数据
                Log.d("TireListActivity", "添加轮胎成功，刷新列表数据");

                // 显示成功提示
                Toast.makeText(this, "添加轮胎成功！", Toast.LENGTH_LONG).show();

                // 延迟一小段时间后刷新数据，确保服务器数据已更新
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // 重新加载轮胎数据
                        loadTires();

                        // 显示刷新提示
                        Snackbar.make(recyclerView, "数据已更新", Snackbar.LENGTH_SHORT).show();
                    }
                }, 500);

            } else if (resultCode == RESULT_CANCELED) {
                // 用户取消了操作
                Log.d("TireListActivity", "用户取消了添加操作");
            } else {
                // 其他结果状态
                Log.d("TireListActivity", "添加操作返回未知状态: " + resultCode);
            }
        }

        // 新增：处理编辑轮胎返回结果
        if (requestCode == REQUEST_CODE_EDIT_TIRE) {
            if (resultCode == RESULT_OK) {
                // 编辑成功，刷新轮胎列表数据
                Log.d("TireListActivity", "编辑轮胎成功，刷新列表数据");

                // 显示成功提示
                Toast.makeText(this, "修改轮胎信息成功！", Toast.LENGTH_LONG).show();

                // 延迟一小段时间后刷新数据，确保服务器数据已更新
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // 重新加载轮胎数据
                        loadTires();

                        // 显示刷新提示
                        Snackbar.make(recyclerView, "数据已更新", Snackbar.LENGTH_SHORT).show();
                    }
                }, 500);
            }
        }
    }

    // 新增：设置自动补全功能
    private void setupAutoComplete() {
        // 初始化适配器
        tireNumberAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_dropdown_item_1line, new ArrayList<>());
        plateNumberAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_dropdown_item_1line, new ArrayList<>());

        // 设置适配器
        etSearchTireNumber.setAdapter(tireNumberAdapter);
        etSearchPlateNumber.setAdapter(plateNumberAdapter);

        // 设置阈值（输入几个字符后开始提示）
        etSearchTireNumber.setThreshold(1);
        etSearchPlateNumber.setThreshold(1);

        // 设置文本变化监听器
        setupTextWatchers();
    }

    // 新增：设置文本变化监听
    private void setupTextWatchers() {
        // 轮胎号输入变化监听
        etSearchTireNumber.addTextChangedListener(new TextWatcher() {
            private Timer timer = new Timer();
            private final long DELAY = 500; // 延迟500毫秒后请求

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                timer.cancel();
                timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        String keyword = s.toString().trim();
                        if (keyword.length() >= 1) {
                            fetchTireNumberSuggestions(keyword);
                        } else {
                            // 清空建议
                            runOnUiThread(() -> {
                                tireNumberAdapter.clear();
                                tireNumberAdapter.notifyDataSetChanged();
                            });
                        }
                    }
                }, DELAY);
            }
        });

        // 车牌号输入变化监听
        etSearchPlateNumber.addTextChangedListener(new TextWatcher() {
            private Timer timer = new Timer();
            private final long DELAY = 500; // 延迟500毫秒后请求

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                timer.cancel();
                timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        String keyword = s.toString().trim();
                        if (keyword.length() >= 1) {
                            fetchPlateNumberSuggestions(keyword);
                        } else {
                            // 清空建议
                            runOnUiThread(() -> {
                                plateNumberAdapter.clear();
                                plateNumberAdapter.notifyDataSetChanged();
                            });
                        }
                    }
                }, DELAY);
            }
        });
    }

    // 新增：获取轮胎号建议
    private void fetchTireNumberSuggestions(String keyword) {
        Call<List<String>> call = apiService.autocompleteTireNumbers(keyword);
        call.enqueue(new Callback<List<String>>() {
            @Override
            public void onResponse(Call<List<String>> call, Response<List<String>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    List<String> suggestions = response.body();
                    runOnUiThread(() -> {
                        tireNumberAdapter.clear();
                        tireNumberAdapter.addAll(suggestions);
                        tireNumberAdapter.notifyDataSetChanged();

                        // 如果有建议且输入框有焦点，显示下拉列表
                        if (!suggestions.isEmpty() && etSearchTireNumber.hasFocus()) {
                            etSearchTireNumber.showDropDown();
                        }
                    });
                    Log.d("TireListActivity", "获取到轮胎号建议: " + suggestions.size() + "条");
                } else {
                    Log.e("TireListActivity", "获取轮胎号建议失败，状态码: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<List<String>> call, Throwable t) {
                Log.e("TireListActivity", "获取轮胎号建议网络错误: " + t.getMessage());
            }
        });
    }

    // 新增：获取车牌号建议
    private void fetchPlateNumberSuggestions(String keyword) {
        Call<List<String>> call = apiService.autocompletePlateNumbers(keyword);
        call.enqueue(new Callback<List<String>>() {
            @Override
            public void onResponse(Call<List<String>> call, Response<List<String>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    List<String> suggestions = response.body();
                    runOnUiThread(() -> {
                        plateNumberAdapter.clear();
                        plateNumberAdapter.addAll(suggestions);
                        plateNumberAdapter.notifyDataSetChanged();

                        // 如果有建议且输入框有焦点，显示下拉列表
                        if (!suggestions.isEmpty() && etSearchPlateNumber.hasFocus()) {
                            etSearchPlateNumber.showDropDown();
                        }
                    });
                    Log.d("TireListActivity", "获取到车牌号建议: " + suggestions.size() + "条");
                } else {
                    Log.e("TireListActivity", "获取车牌号建议失败，状态码: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<List<String>> call, Throwable t) {
                Log.e("TireListActivity", "获取车牌号建议网络错误: " + t.getMessage());
            }
        });
    }

    private void setupEmptySpinners() {
        // 设置空的运输公司下拉列表
        List<String> emptyCompanies = new ArrayList<>();
        emptyCompanies.add("加载中...");
        ArrayAdapter<String> companyAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, emptyCompanies);
        companyAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerCompany.setAdapter(companyAdapter);

        // 设置空的状态下拉列表
        List<String> emptyStatus = new ArrayList<>();
        emptyStatus.add("加载中...");
        ArrayAdapter<String> statusAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, emptyStatus);
        statusAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerStatus.setAdapter(statusAdapter);
    }

    private void setupRecyclerView() {
        adapter = new TireListAdapter(tireList, new TireListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Tire tire) {
                showTireDetail(tire);
            }

            @Override
            public void onDetailClick(Tire tire) {
                showTireDetail(tire);
            }

            @Override
            public void onRepairClick(Tire tire) {
                // 已移除修补功能，此方法不再使用
            }

            @Override
            public void onEditClick(Tire tire) {
                showEditForm(tire);
            }
        });

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
    }

    private void setupRetrofit() {
        // 使用统一的 ApiClient
        Retrofit retrofit = ApiClient.getClient();
        if (retrofit != null) {
            apiService = retrofit.create(TireApiService.class);
            Log.d("TireListActivity", "使用统一的 ApiClient 配置");
        } else {
            Log.e("TireListActivity", "ApiClient 初始化失败");
            Toast.makeText(this, "网络初始化失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void setupSearch() {
        // 搜索按钮点击事件
        findViewById(R.id.btn_search).setOnClickListener(v -> loadTires());

        // 重置按钮点击事件
        findViewById(R.id.btn_reset).setOnClickListener(v -> {
            etSearchTireNumber.setText("");

            // 根据角色决定是否重置车牌号
            if (!"DRIVER".equals(userRole)) {
                etSearchPlateNumber.setText("");
            } else {
                // 司机角色保持固定车牌号
                if (userPlateNumber != null && !userPlateNumber.isEmpty()) {
                    etSearchPlateNumber.setText(userPlateNumber);
                }
            }

            spinnerCompany.setSelection(0);
            spinnerStatus.setSelection(0);
            loadTires();
        });
    }






    /**
     * 设置固定运输公司（非管理员角色）
     */
    private void setupFixedTransportCompany() {
        transportCompanies = new ArrayList<>();

        if (userCompany != null && !userCompany.isEmpty()) {
            transportCompanies.add(userCompany);
        } else {
            transportCompanies.add("当前公司");
        }

        // 非管理员角色不需要"全部"选项，因为只能查看自己公司的数据
        updateCompanySpinner();

        // 设置选中第一个（也是唯一一个）
        if (spinnerCompany.getAdapter() != null && spinnerCompany.getAdapter().getCount() > 0) {
            spinnerCompany.setSelection(0);
        }

        // 加载轮胎数据
        loadTires();
    }

    /**
     * 加载状态选项
     */
    private void loadStatusOptions() {
        Log.d("TireListActivity", "开始加载状态选项");

        Call<List<String>> statusCall = apiService.getStatusOptions();
        statusCall.enqueue(new Callback<List<String>>() {
            @Override
            public void onResponse(Call<List<String>> call, Response<List<String>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    statusOptions = response.body();
                    // 在列表开头添加"全部"选项
                    statusOptions.add(0, "全部状态");
                    updateStatusSpinner();
                    Log.d("TireListActivity", "加载状态选项成功: " + statusOptions.size() + "个");
                } else {
                    // 如果失败，只保留"全部"选项
                    statusOptions = new ArrayList<>();
                    statusOptions.add("全部状态");
                    updateStatusSpinner();
                    showError("加载状态选项失败");
                    Log.e("TireListActivity", "加载状态选项失败，状态码: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<List<String>> call, Throwable t) {
                // 如果失败，只保留"全部"选项
                statusOptions = new ArrayList<>();
                statusOptions.add("全部状态");
                updateStatusSpinner();
                showError("加载状态选项失败: " + t.getMessage());
                Log.e("TireListActivity", "加载状态选项网络错误: " + t.getMessage());
            }
        });
    }



    private void updateStatusSpinner() {
        ArrayAdapter<String> statusAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, statusOptions);
        statusAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerStatus.setAdapter(statusAdapter);
    }

    private void loadTires() {
        showLoading(true);



        // 使用统一的 ApiClient
        Retrofit retrofit = ApiClient.getClient();
        if (retrofit == null) {
            Log.e("TireListActivity", "ApiClient 不可用");
            return;
        }

        TireApiService authenticatedApiService = retrofit.create(TireApiService.class);
        // 根据用户角色构建搜索参数
        String tireNumber = etSearchTireNumber.getText().toString().trim();
        String plateNumber = etSearchPlateNumber.getText().toString().trim();
        String company = "";
        String status = "";

        // 设置运输公司参数
        if ("ADMIN".equals(userRole)) {
            // 管理员：使用选择的运输公司
            if (spinnerCompany.getSelectedItemPosition() > 0) {
                company = spinnerCompany.getSelectedItem().toString();
            }
        } else {
            // 非管理员：使用固定运输公司
            if (userCompany != null && !userCompany.isEmpty()) {
                company = userCompany;
            }
        }

        // 设置车牌号参数（司机角色使用固定车牌号）
        if ("DRIVER".equals(userRole)) {
            if (userPlateNumber != null && !userPlateNumber.isEmpty()) {
                plateNumber = userPlateNumber;
            }
        }

        // 设置状态参数
        if (spinnerStatus.getSelectedItemPosition() > 0) {
            String selectedStatus = spinnerStatus.getSelectedItem().toString();
            if ("使用中".equals(selectedStatus)) {
                status = "active";
            } else if ("已报废".equals(selectedStatus)) {
                status = "scrapped";
            }
        }

        Call<Map<String, Object>> call = authenticatedApiService.searchTires(tireNumber, plateNumber, company, status);
        call.enqueue(new Callback<Map<String, Object>>() {
            @Override
            public void onResponse(Call<Map<String, Object>> call, Response<Map<String, Object>> response) {
                showLoading(false);

                if (response.isSuccessful() && response.body() != null) {
                    Map<String, Object> data = response.body();
                    List<Map<String, Object>> tiresData = (List<Map<String, Object>>) data.get("tires");
                    updateTireList(tiresData);

                    Map<String, Object> stats = (Map<String, Object>) data.get("statistics");
                    updateStatistics(stats);
                } else {
                    if (response.code() == 401) {
                        // 未授权，跳转到登录页面
                        showError("登录已过期，请重新登录");
                        clearLoginStatus();
                    } else {
                        showError("加载数据失败");
                    }
                }
            }

            @Override
            public void onFailure(Call<Map<String, Object>> call, Throwable t) {
                showLoading(false);
                showError("网络连接失败");
            }
        });
    }

    private void updateTireList(List<Map<String, Object>> tiresData) {
        tireList.clear();
        if (tiresData != null && !tiresData.isEmpty()) {
            for (Map<String, Object> tireData : tiresData) {
                Tire tire = convertMapToTire(tireData);
                tireList.add(tire);
            }
        }
        adapter.updateData(tireList);

        // 如果没有数据，显示空状态
        if (tireList.isEmpty()) {
            showEmptyState();
        }
    }

    private Tire convertMapToTire(Map<String, Object> tireData) {
        Tire tire = new Tire();

        // 设置基本属性
        if (tireData.get("id") != null) {
            tire.setId(((Double) tireData.get("id")).longValue());
        }
        tire.setTireNumber((String) tireData.get("tireNumber"));
        tire.setVehiclePlateNumber((String) tireData.get("vehiclePlateNumber"));
        tire.setTrailerPlateNumber((String) tireData.get("trailerPlateNumber"));
        tire.setTireModel((String) tireData.get("tireModel"));
        tire.setTireBrand((String) tireData.get("tireBrand"));
        tire.setInstallDate((String) tireData.get("installDate"));
        tire.setScrapDate((String) tireData.get("scrapDate"));
        tire.setTransportCompany((String) tireData.get("transportCompany"));
        tire.setTirePosition((String) tireData.get("tirePosition"));
        tire.setPosition((String) tireData.get("position"));

        // 设置数值型属性
        if (tireData.get("installMileage") != null) {
            tire.setInstallMileage(((Double) tireData.get("installMileage")).intValue());
        }
        if (tireData.get("currentMileage") != null) {
            tire.setCurrentMileage(((Double) tireData.get("currentMileage")).intValue());
        }
        if (tireData.get("axleNumber") != null) {
            tire.setAxleNumber(((Double) tireData.get("axleNumber")).intValue());
        }

        // 设置状态
        if (tireData.get("scrapDate") != null) {
            tire.setStatus("已报废");
        } else {
            tire.setStatus("使用中");
        }

        return tire;
    }

    private void updateStatistics(Map<String, Object> stats) {
        if (stats != null) {
            tvTotalTires.setText(String.valueOf(stats.get("totalTires")));
            tvActiveTires.setText(String.valueOf(stats.get("activeTires")));
            tvScrappedTires.setText(String.valueOf(stats.get("scrappedTires")));
            tvRepairedTires.setText(String.valueOf(stats.get("repairedTires")));
        } else {
            resetStatistics();
        }
    }

    private void resetStatistics() {
        tvTotalTires.setText("0");
        tvActiveTires.setText("0");
        tvScrappedTires.setText("0");
        tvRepairedTires.setText("0");
    }

    private void showLoading(boolean show) {
        progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        recyclerView.setVisibility(show ? View.GONE : View.VISIBLE);
    }

    private void showError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    private void showEmptyState() {
        // 这里可以添加一个空状态视图
        // 例如显示"暂无数据"的提示
        Toast.makeText(this, "暂无轮胎数据", Toast.LENGTH_SHORT).show();
    }

    // 以下方法为占位方法，后续实现具体功能
    private void showTireDetail(Tire tire) {
        Intent intent = new Intent(this, TireDetailActivity.class);
        intent.putExtra("tire", tire);
        startActivity(intent);
    }

    private void showRepairForm(Tire tire) {
        // 已移除修补功能，此方法不再使用
    }

    /**
     * 显示修改轮胎信息表单
     */
    private void showEditForm(Tire tire) {
        Intent intent = new Intent(this, EditTireActivity.class);
        intent.putExtra("tire", tire);
        startActivityForResult(intent, REQUEST_CODE_EDIT_TIRE);
    }


    // 在 TireListActivity 类中添加以下方法

    /**
     * 根据用户角色加载运输公司数据
     */
    private void loadTransportCompaniesByRole() {
        showLoading(true);

        switch (userRole) {
            case "ADMIN":
                // 管理员：从服务器获取所有运输公司
                loadAllTransportCompanies();
                break;
            case "COMPANY":
                // 运输公司：使用当前用户的公司
                setupCurrentUserCompany();
                break;
            case "DRIVER":
                // 司机：使用当前用户的公司
                setupCurrentUserCompany();
                break;
            default:
                // 默认：使用当前用户的公司
                setupCurrentUserCompany();
                break;
        }
    }

    /**
     * 加载所有运输公司（管理员专用）
     */
    private void loadAllTransportCompanies() {
        Log.d("TireListActivity", "开始加载所有运输公司（管理员）");

        Call<List<String>> companiesCall = apiService.getTransportCompanies();
        companiesCall.enqueue(new Callback<List<String>>() {
            @Override
            public void onResponse(Call<List<String>> call, Response<List<String>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    transportCompanies = response.body();
                    // 在列表开头添加"全部"选项
                    transportCompanies.add(0, "全部运输公司");
                    updateCompanySpinner();
                    Log.d("TireListActivity", "管理员加载运输公司成功: " + transportCompanies.size() + "个");

                    // 加载轮胎数据
                    loadTires();
                } else {
                    // 如果失败，使用默认选项
                    setupDefaultCompanies();
                    showError("加载运输公司失败，状态码: " + response.code());
                    Log.e("TireListActivity", "加载运输公司失败，状态码: " + response.code());

                    // 仍然加载轮胎数据
                    loadTires();
                }
            }

            @Override
            public void onFailure(Call<List<String>> call, Throwable t) {
                // 如果失败，使用默认选项
                setupDefaultCompanies();
                showError("加载运输公司失败: " + t.getMessage());
                Log.e("TireListActivity", "加载运输公司网络错误: " + t.getMessage());

                // 仍然加载轮胎数据
                loadTires();
            }
        });
    }

    /**
     * 设置当前用户所属的公司（非管理员角色）
     */
    private void setupCurrentUserCompany() {
        Log.d("TireListActivity", "设置当前用户公司 - 公司: " + userCompany);

        transportCompanies = new ArrayList<>();

        if (userCompany != null && !userCompany.isEmpty()) {
            transportCompanies.add(userCompany);
            Log.d("TireListActivity", "设置用户公司: " + userCompany);
        } else {
            // 如果用户公司信息为空，尝试从SharedPreferences重新获取
            userCompany = sharedPreferences.getString("company", "");
            if (!userCompany.isEmpty()) {
                transportCompanies.add(userCompany);
                Log.d("TireListActivity", "从SharedPreferences获取公司: " + userCompany);
            } else {
                transportCompanies.add("当前公司");
                Log.w("TireListActivity", "用户公司信息为空");
            }
        }

        updateCompanySpinner();

        // 设置选中第一个（也是唯一一个）
        if (spinnerCompany.getAdapter() != null && spinnerCompany.getAdapter().getCount() > 0) {
            spinnerCompany.setSelection(0);
        }

        // 加载轮胎数据
        loadTires();
    }

    /**
     * 设置默认运输公司选项（用于失败情况）
     */
    private void setupDefaultCompanies() {
        transportCompanies = new ArrayList<>();
        if ("ADMIN".equals(userRole)) {
            transportCompanies.add("全部运输公司");
            Log.d("TireListActivity", "设置默认选项：全部运输公司");
        } else if (userCompany != null && !userCompany.isEmpty()) {
            transportCompanies.add(userCompany);
            Log.d("TireListActivity", "设置默认选项：用户公司 " + userCompany);
        } else {
            transportCompanies.add("当前公司");
            Log.d("TireListActivity", "设置默认选项：当前公司");
        }
        updateCompanySpinner();
    }

    /**
     * 更新运输公司下拉框的显示
     */
    private void updateCompanySpinner() {
        runOnUiThread(() -> {
            ArrayAdapter<String> companyAdapter = new ArrayAdapter<>(this,
                    android.R.layout.simple_spinner_item, transportCompanies);
            companyAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerCompany.setAdapter(companyAdapter);

            // 根据角色设置下拉框的可用性
            spinnerCompany.setEnabled("ADMIN".equals(userRole));

            Log.d("TireListActivity", "更新运输公司下拉框，数量: " + transportCompanies.size() +
                    ", 启用状态: " + spinnerCompany.isEnabled());
        });
    }

    /**
     * 更新车牌号输入框的显示
     */
    private void updatePlateNumberField() {
        runOnUiThread(() -> {
            if ("DRIVER".equals(userRole)) {
                // 司机角色：固定车牌号
                etSearchPlateNumber.setEnabled(false);
                if (userPlateNumber != null && !userPlateNumber.isEmpty()) {
                    etSearchPlateNumber.setText(userPlateNumber);
                } else {
                    // 如果用户车牌号信息为空，尝试从SharedPreferences重新获取
                    userPlateNumber = sharedPreferences.getString("plateNumber", "");
                    if (!userPlateNumber.isEmpty()) {
                        etSearchPlateNumber.setText(userPlateNumber);
                    }
                }
                etSearchPlateNumber.setHint("固定车牌号");
            } else {
                // 其他角色：可编辑车牌号
                etSearchPlateNumber.setEnabled(true);
                etSearchPlateNumber.setHint("输入车牌号搜索");
            }

            Log.d("TireListActivity", "更新车牌号字段，启用状态: " + etSearchPlateNumber.isEnabled() +
                    ", 车牌号: " + userPlateNumber);
        });
    }



    /**
     * 获取完整的用户信息
     */
    private void fetchCompleteUserInfo() {
        // 使用统一的 ApiClient
        Retrofit retrofit = ApiClient.getClient();
        if (retrofit == null) {
            Log.e("TireListActivity", "ApiClient 不可用");
            return;
        }

        // 创建AuthApiService接口
        AuthApiService authApiService = retrofit.create(AuthApiService.class);

        Call<Map<String, Object>> call = authApiService.getUserInfo();
        call.enqueue(new Callback<Map<String, Object>>() {
            @Override
            public void onResponse(Call<Map<String, Object>> call, Response<Map<String, Object>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    Map<String, Object> data = response.body();
                    Boolean authenticated = (Boolean) data.get("authenticated");

                    if (authenticated != null && authenticated) {
                        Map<String, Object> userMap = (Map<String, Object>) data.get("user");
                        if (userMap != null) {
                            // 更新用户信息
                            updateUserInfoFromServer(userMap);
                            Log.d("TireListActivity", "获取完整用户信息成功");
                        }
                    } else {
                        Log.e("TireListActivity", "获取用户信息失败: 未认证");
                        // 如果认证失败，跳转到登录页
                        handleUnauthorizedError();
                    }
                } else {
                    Log.e("TireListActivity", "获取用户信息失败，状态码: " + response.code());
                    if (response.code() == 401) {
                        handleUnauthorizedError();
                    }
                }
            }

            @Override
            public void onFailure(Call<Map<String, Object>> call, Throwable t) {
                Log.e("TireListActivity", "获取用户信息网络错误: " + t.getMessage());
            }
        });
    }


    /**
     * 处理认证错误
     */
    private void handleUnauthorizedError() {
        runOnUiThread(() -> {
            Log.e("TireListActivity", "Session 认证失败，需要重新登录");
            Toast.makeText(TireListActivity.this, "登录已过期，请重新登录", Toast.LENGTH_LONG).show();

            // 清除用户数据
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.clear();
            editor.apply();

            // 跳转到登录页面
            Intent intent = new Intent(TireListActivity.this, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        });
    }


    /**
     * 从服务器响应更新用户信息
     */
    private void updateUserInfoFromServer(Map<String, Object> userMap) {
        SharedPreferences.Editor editor = sharedPreferences.edit();

        // 更新公司信息
        if (userMap.get("transportCompany") != null) {
            userCompany = userMap.get("transportCompany").toString();
            editor.putString("company", userCompany);
        } else {
            userCompany = "";
            editor.putString("company", "");
        }

        // 更新车牌信息
        if (userMap.get("vehiclePlateNumber") != null) {
            userPlateNumber = userMap.get("vehiclePlateNumber").toString();
            editor.putString("plateNumber", userPlateNumber);
        } else {
            userPlateNumber = "";
            editor.putString("plateNumber", "");
        }

        editor.apply();

        Log.d("TireListActivity", "更新后的用户信息 - 公司: " + userCompany + ", 车牌: " + userPlateNumber);

        // 更新UI
        runOnUiThread(() -> {
            updateCompanySpinner();
            updatePlateNumberField();
            loadTires(); // 重新加载数据
        });
    }


}